package com.wcgksoft.controller.goods;

import com.wcgksoft.common.util.FileUtil;
import com.wcgksoft.common.util.Layui;
import com.wcgksoft.common.util.MultipartFileToFile;
import com.wcgksoft.entity.goods.Goods;
import com.wcgksoft.service.goods.GoodsService;
import net.sf.json.JSONObject;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author 御风
 * @version V1.0
 * @Package com.wcgksoft.controller.goods
 * @Description TODO 商品
 * @date 2020/5/12 16:11
 * @ClassName GoodsController
 */
@Controller
@RequestMapping("goods/list")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @ResponseBody
    @RequestMapping(value = "find")
    public Layui findAll(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "limit", required = false) Integer limit) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Goods.class);
        criteria.addOrder(Order.desc("createTime"));
        List<Goods> list = goodsService.findByConditions(criteria, page, limit);
        return Layui.data(0, "查询成功", goodsService.getTotalCount(), list);
    }


    @ResponseBody
    @RequestMapping(value = "findAll")
    public Layui findAllGoods() {
        DetachedCriteria criteria = DetachedCriteria.forClass(Goods.class);
        List<Goods> list = goodsService.findByConditions(criteria);
        return Layui.data(0, "查询成功", goodsService.getTotalCount(), list);
    }

    /**
     * 添加
     */
    @ResponseBody
    @RequestMapping(value = "update")
    public Layui update(@RequestParam(value = "data", required = false) String data){
        JSONObject param = JSONObject.fromObject(data);
        if (param == null) {
            return Layui.data(1, "请求格式有误", 0, null);
        } else {
            Goods goods = (Goods) JSONObject.toBean(JSONObject.fromObject(data), Goods.class);
            goods.setCreateTime(new Date());
            goodsService.saveOrUpdate(goods);
            return Layui.data(0, "保存成功", 1, Layui.addList(goods));
        }
    }
    /**
     * 删除
     * @param id
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value="delete")
    public Layui delete(@RequestParam(value = "id") Integer id){
        Goods goods=goodsService.findById(id);
        goodsService.delete(goods);
        return Layui.data(1,"删除成功",1,null);
    }
}
